package com.xh.bussiness.tools.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.course.model.Course;
import com.xh.bussiness.course.model.CourseIndex;
import com.xh.bussiness.course.service.ICourseIndexService;
import com.xh.bussiness.course.service.ICourseService;
import com.xh.bussiness.permission.bean.request.UserRequest;
import com.xh.bussiness.permission.model.Role;
import com.xh.bussiness.permission.model.School;
import com.xh.bussiness.permission.service.IRoleService;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.permission.util.UserAuthUtil;
import com.xh.bussiness.resource.model.Material;
import com.xh.bussiness.resource.model.MaterialChapter;
import com.xh.bussiness.resource.model.MaterialCourseIndex;
import com.xh.bussiness.resource.model.MaterialPrepare;
import com.xh.bussiness.resource.service.IMaterialChapterService;
import com.xh.bussiness.resource.service.IMaterialCourseIndexService;
import com.xh.bussiness.resource.service.IMaterialPrepareService;
import com.xh.bussiness.resource.service.IMaterialService;
import com.xh.bussiness.system.bean.dto.DictionaryBean;
import com.xh.bussiness.system.model.*;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.*;
import com.xh.bussiness.tiku.bean.dto.BookChapterDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.bean.request.QuestionSaveRequest;
import com.xh.bussiness.tiku.bean.request.SaveKnowledgeRequest;
import com.xh.bussiness.tiku.constant.QuestionConstant;
import com.xh.bussiness.tiku.dao.QuestionMapper;
import com.xh.bussiness.tiku.model.*;
import com.xh.bussiness.tiku.service.*;
import com.xh.bussiness.tools.constants.UrlConstants;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.DateUtils;
import com.xh.core.util.HttpUtils;
import com.xh.core.util.RegexUtils;
import com.xh.core.util.StringUtils;
import com.xh.one2one.knowledgeSystem.model.*;
import com.xh.one2one.knowledgeSystem.service.*;
import com.xh.one2one.teachHandout.model.HandoutContent;
import com.xh.one2one.teachHandout.model.HandoutNode;
import com.xh.one2one.teachHandout.service.IHandoutContentService;
import com.xh.one2one.teachHandout.service.IHandoutNodeService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class GetDataService extends BaseServiceImpl<QuestionMapper, Question> {

    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IDictionaryRelService dictionaryRelService;
    @Autowired
    private IQuestionTypeRelationService questionTypeRelationService;
    @Autowired
    private IKnowledgeService knowledgeService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private ICourseIndexService courseIndexService;
    @Autowired
    private IMaterialService materialService;
    @Autowired
    private IMaterialCourseIndexService materialCourseIndexService;
    @Autowired
    private IMaterialPrepareService materialPrepareService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPaperService paperService;
    @Autowired
    private ISchoolService schoolService;
    @Autowired
    private IKnowledgeTemplateService knowledgeTemplateService;
    @Autowired
    private IKnowledgeTemplateModuleService knowledgeTemplateModuleService;
    @Autowired
    private IKnowledgeElementService knowledgeElementService;
    @Autowired
    private IKnowledgeManagerService knowledgeManagerService;
    @Autowired
    private IKnowledgeContentService knowledgeContentService;
    @Autowired
    private IHandoutNodeService handoutNodeService;
    @Autowired
    private IHandoutContentService handoutContentService;
    @Autowired
    private ICourseSystemService courseSystemService;
    @Autowired
    private IKnowledgeManagerElementRelationService knowledgeManagerElementRelationService;
    @Autowired
    private IBookVersionService bookVersionService;
    @Autowired
    private IBookChapterService bookChapterService;
    @Autowired
    private IMaterialChapterService materialChapterService;

    /**
     * 角色
     *
     * @return
     */
    public String getRoles() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_ROLE, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Role role = new Role();
            role.setId(data.getLong("id").toString());
            role.setName(data.getString("name"));
            role.setStatus(0);
            role.setDeleted(0);
            roleService.insert(role);
        }
        return "成功了";
    }

    public String getBasicData() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_BASIC_DATA, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");

        List<Dictionary> basicDatas = new ArrayList<>(datas.size());


        List<DictionaryBean> list = new ArrayList<>();
        int index = 0;
        // 年份 季节 年级 学科 班型 教材版本
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            String typeCode = getTypeCode(data.getString("type"));
            if (StringUtils.isEmpty(typeCode)) {
                continue;
            }
//            if (typeCode.equals("SUBJECT")) {
//                String xdName = data.getString("XD_ID_name");
//                if (xdName.equals("小学")) {
//                    dictionary.setParentCode("primary");
//                } else if (xdName.equals("初中")) {
//                    dictionary.setParentCode("middle");
//                } else if (xdName.equals("高中")) {
//                    dictionary.setParentCode("high");
//                }
//                dictionary.setParentTypeCode("GRADE_RANGE");
//            }
            DictionaryBean dictionary = new DictionaryBean();
            dictionary.setCode(data.getLong("id").toString());
            dictionary.setVal(data.getLong("id").toString());
            dictionary.setTypeCode(typeCode);
            dictionary.setOrderNo(index++);
            dictionary.setName(data.getString("name"));
            dictionary.setCreatorName(data.getString("operatorName"));
            dictionary.setModifierName(data.getString("updateName"));
            dictionary.setModifyTime(data.getString("updateTime") == null ? null : DateUtils.parse(data.getString("updateTime"), "yyyy-MM-dd HH:mm:ss"));
            list.add(dictionary);

//            QueryWrapper<Dictionary> qw = new QueryWrapper<>();
//            qw.eq("type_code", typeCode);
//            dictionaryService.deleteByCondition(qw);
//            QueryWrapper<DictionaryRel> qw1 = new QueryWrapper<>();
//            qw1.eq("child_type_code", typeCode);
//            dictionaryRelService.deleteByCondition(qw1);
        }
        for (DictionaryBean dictionaryBean : list) {
            dictionaryService.saveObj(dictionaryBean);
        }
        return "成功了";
    }

    public String getSubject() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_BASIC_DATA_BOOK_SUBJECT, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        int index = 0;
        List<String> gradeRanges = new ArrayList<>(Arrays.asList("primary", "middle", "high"));
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            for (String gradeRange : gradeRanges) {
                DictionaryBean dictionary = new DictionaryBean();
                dictionary.setParentCode(gradeRange);
                dictionary.setParentTypeCode("GRADE_RANGE");
                dictionary.setCode(gradeRange + "-" + data.getLong("id").toString());
                dictionary.setVal(data.getLong("id").toString());
                dictionary.setTypeCode("SUBJECT");
                dictionary.setOrderNo(index++);
                if("primary".equals(gradeRange)){
                    dictionary.setName("小学" +data.getString("name"));
                }else if("middle".equals(gradeRange)){
                    dictionary.setName("初中" +data.getString("name"));
                }else{
                    dictionary.setName("高中" +data.getString("name"));
                }
                dictionary.setModifyTime(data.getString("updateTime") == null ? null : DateUtils.parse(data.getString("updateTime"), "yyyy-MM-dd HH:mm:ss"));
                dictionaryService.saveObj(dictionary);
            }
        }
        return "成功了";
    }

    public String getBookVersion() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_BASIC_DATA_BOOK_VERSION, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");

        int index = 0;
        // 年份 季节 年级 学科 班型 教材版本
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            String typeCode = "TEACH_BOOK_VERSION";
            Dictionary dictionary = new Dictionary();
            dictionary.setId(data.getLong("id").toString());
            dictionary.setCode(data.getLong("id").toString());
            dictionary.setVal(data.getLong("id").toString());
            dictionary.setTypeCode(typeCode);
            dictionary.setOrderNo(index++);
            dictionary.setName(data.getString("name"));
            dictionary.setCreatorName(data.getString("operatorName"));
            dictionary.setModifierName(data.getString("updateName"));
            dictionary.setModifyTime(data.getString("updateTime") == null ? null : DateUtils.parse(data.getString("updateTime"), "yyyy-MM-dd HH:mm:ss"));
            dictionaryService.insert(dictionary);
            CourseSystem courseSystem = new CourseSystem();
            String gradeRange = getGradeRange(data.getLong("XD_ID"));
            courseSystem.setSubjectId(gradeRange + "-" + data.getString("XK_ID"));
            String subjectName = null;
            if("primary".equals(gradeRange)){
                subjectName = "小学" + data.getString("XK_ID_name");
            }else if("middle".equals(gradeRange)){
                subjectName = "初中" + data.getString("XK_ID_name");
            }else {
                subjectName = "高中" + data.getString("XK_ID_name");
            }
            courseSystem.setSubjectName(subjectName);
            courseSystem.setRelationType("TEACH_BOOK_VERSION");
            courseSystem.setRelationValue(data.getLong("id").toString());
            courseSystem.setRelationName(data.getString("name"));
            courseSystemService.insert(courseSystem);
        }
        return "成功了";
    }

//    private String getGradeRange(String grandRangeName) {
//        switch (grandRangeName) {
//            case "小学":
//                return "primary";
//            case "小升初":
//                return "primary";
//            case "初中":
//                return "middle";
//            case "中考":
//                return "middle";
//            case "高中":
//                return "high";
//            case "高考":
//                return "high";
//
//        }
//        return "primary";
//    }

    private String getGradeRange(Long grandRangeId) {
        if (grandRangeId.equals(157L) || grandRangeId.equals(153L)) {
            return "primary";
        } else if (grandRangeId.equals(164L) || grandRangeId.equals(142L)) {
            return "middle";
        } else if (grandRangeId.equals(152L) || grandRangeId.equals(143L)) {
            return "high";
        }
        return "primary";
    }

    public String getQuestion() {
//        questionService.deleteAll();
        for (int i = 0; i < 1000; i++) {
            String resultStr = HttpUtils.postRequest(UrlConstants.URL_QUESTION + "?page=" + (i + 1) + "&pageSize=3000", null);
            JSONObject result = JSON.parseObject(resultStr);
            if (result == null || result.getJSONObject("obj") == null) {
                return "失败了";
            }
            JSONArray datas = result.getJSONObject("obj").getJSONArray("list");
            for (Object data : datas) {
                JSONObject json = JSON.parseObject(data.toString());
                Integer status = json.getInteger("status");
                if (status == null || status != 1) {
                    continue;
                }
                String subjectCode = getGradeRange(json.getLong("studyStageId")) + "-" + json.getLong("subjectId");

                // 题型
                String type = json.getString("type");
                String typeName = json.getString("typeName");
                QuestionTypeRelation questionTypeRelation = questionTypeRelationService.queryByJyQuesTypeName(subjectCode, getQuestionType(type));
                if (questionTypeRelation == null) {
                    continue;
                }
                // 难度
                Integer difficultId = json.getInteger("QL_ID") == null ? null : json.getInteger("QL_ID") + 10;

                // 年级
                String gradeName = json.getString("NJ_name");
                List<Dictionary> grades = dictionaryService.queryByName("GRADE", gradeName);
                String gradeId = null;
                if (!grades.isEmpty()) {
                    gradeId = grades.get(0).getId();
                }

                // 年份
                String yearName = json.getString("year");
                List<Dictionary> years = dictionaryService.queryByName("YEAR", yearName);
                String yearId = null;
                if (!years.isEmpty()) {
                    yearId = years.get(0).getId();
                }

                List<QuestionSource> questionSources = new ArrayList<>();
                if (yearId != null) {
                    QuestionSource questionSource = new QuestionSource();
                    questionSource.setYear(yearId);
                    questionSource.setYearName(yearName);
                    questionSources.add(questionSource);
                }

                // 知识点
                JSONArray knowledges = json.getJSONArray("zsd_id");
                List<Integer> knowledgeIds = new ArrayList<>();
                if (json.getJSONArray("zsd_id") != null) {
                    knowledgeIds = JSON.parseObject(knowledges.toJSONString(), List.class);
                }
                List<QuestionDto> questionDtos = new ArrayList<>();
                // 选项
                JSONArray newOptions = null;
                JSONArray options = json.getJSONArray("options");
                if (type.equals("ST_dx") || type.equals("ST_dxx")) {
                    if (options != null && !options.isEmpty()) {
                        newOptions = new JSONArray(options.size());
                        int index = 0;
                        for (Object obj : options) {
                            JSONObject option = JSON.parseObject(obj.toString());
                            JSONObject newOption = new JSONObject();
                            newOption.put("no", ++index);
                            newOption.put("name", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                            newOption.put("content", option.getString("name"));
                            newOptions.add(newOption);
                        }
                    }
                } else if (type.equals("ST_wxtk")) {
                    JSONArray questions = json.getJSONArray("questions");
                    if(questions == null || questions.isEmpty()){
                        continue;
                    }
                    newOptions = new JSONArray(questions.size());
                    int i1 = 0;
                    for (Object obj : questions) {
                        i1++;
                        JSONObject question = JSON.parseObject(obj.toString());
                        JSONObject option = new JSONObject();
                        option.put("name", i1 + "");
                        JSONArray childs = new JSONArray();
                        JSONArray optionArray = question.getJSONArray("options");
                        int index = 0;
                        for (Object o : optionArray) {
                            index++;
                            JSONObject optionChild = new JSONObject();
                            optionChild.put("no", index);
                            optionChild.put("name", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                            JSONObject option1 = JSON.parseObject(o.toString());
                            optionChild.put("content", option1.getString("name"));
                            childs.add(optionChild);
                        }
                        option.put("childs", childs);
                        newOptions.add(option);
                    }
                } else if (type.equals("ST_ydlj")) {
                    JSONArray questions = json.getJSONArray("questions");
                    if (questions != null && questions.size() != 0) {

                        for (Object obj : questions) {
                            QuestionDto questionDto = new QuestionDto();
                            JSONObject question = JSON.parseObject(obj.toString());
                            questionDto.setTitle(question.getString("name"));
                            JSONArray optionArray = question.getJSONArray("options");
                            int index = 0;
                            if (optionArray != null) {
                                JSONArray newOptions1 = new JSONArray(optionArray.size());
                                for (Object obj1 : optionArray) {
                                    index++;
                                    JSONObject option = JSON.parseObject(obj1.toString());
                                    JSONObject newOption = new JSONObject();
                                    newOption.put("no", index);
                                    newOption.put("name", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                                    newOption.put("content", option.getString("name"));
                                    newOptions1.add(newOption);
                                }
                                questionDto.setOption(newOptions1);
                            }
                            questionDtos.add(questionDto);
                        }
                    }
                }
                // 解答

                QuestionSaveRequest question = new QuestionSaveRequest();
                question.setId(json.getLong("id").toString());
                question.setTitle(json.getString("name"));
                question.setSubjectId(subjectCode);
                question.setType(questionTypeRelation.getJyQuestionType());

                // 选项
                question.setOption(newOptions);

                // 设置属性
                question.setDifficult(difficultId);
                question.setGradeId(gradeId);
                question.setQuestionSources(questionSources);
                // 设置知识点
                question.setKnowledgePoints(knowledgeIds.stream().map(id -> id + "").collect(Collectors.toList()));

                // 设置答案
                question.setRightAnswer(getAnswers(json));
                question.setAnalysis(json.getString("jx"));

                question.setChilds(questionDtos);
                questionService.addQuestion_syncData(question);
            }
            if (datas.size() < 3000) {
                break;
            }
        }

        return "成功了";
    }

    public JSONArray getAnswers(JSONObject json) {
        String type = json.getString("type");
        // 答案
        JSONArray answers = new JSONArray();
        JSONArray options = json.getJSONArray("options");
        // 单选题  多选题
        if (type.equals("ST_dx") || type.equals("ST_dxx")) {
            if (options != null && !options.isEmpty()) {
                int index = 0;
                for (Object obj : options) {
                    index++;
                    JSONObject option = JSON.parseObject(obj.toString());
                    Integer isTrue = option.getInteger("isTrue");
                    if (isTrue != null && isTrue == 1) {
                        JSONObject answer = new JSONObject();
                        answer.put("no", index);
                        answer.put("name", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                        answer.put("content", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                        answers.add(answer);
                    }
                }
            }
        }

        // 填空题
        if (type.equals("ST_tk")) {
            if (options != null && !options.isEmpty()) {
                int index = 0;
                for (Object obj : options) {
                    index++;
                    JSONObject option = JSON.parseObject(obj.toString());
                    JSONObject answer = new JSONObject();
                    answer.put("no", 1);
                    answer.put("name", option.getString("name"));
                    answer.put("content", option.getString("name"));
                    answers.add(answer);
                }
            }
        }

        // 判断题
        if (type.equals("ST_pd")) {
            Integer isTrue = json.getInteger("isTrue");
            JSONObject answer = new JSONObject();
            answer.put("no", 1);
            answer.put("name", isTrue == 1 ? "正确" : "错误");
            answer.put("content", isTrue == 1 ? "正确" : "错误");
            answers.add(answer);
        }

        // 解答题
        if (type.equals("ST_jd") || type.equals("ST_zw")) {
            JSONObject answer = new JSONObject();
            answer.put("no", 1);
            answer.put("name", json.getString("answer"));
            answer.put("content", json.getString("answer"));
            answers.add(answer);
        }

        // 完形填空、阅读理解
        if (type.equals("ST_wxtk") || type.equals("ST_ydlj")) {
            JSONArray questions = json.getJSONArray("questions");
            for (Object obj : questions) {
                JSONObject question = JSON.parseObject(obj.toString());
                if (question.getString("type").equals("ST_dx")) {
                    JSONArray optionArray = question.getJSONArray("options");
                    int index = 0;
                    for (Object o : optionArray) {
                        JSONObject option = JSON.parseObject(o.toString());
                        Integer isTrue = option.getInteger("isTrue");
                        if (isTrue != null && isTrue == 1) {
                            index++;
                            JSONObject answer = new JSONObject();
                            answer.put("no", index);
                            answer.put("name", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                            answer.put("content", QuestionConstant.OPTION_ORDER.toCharArray()[index - 1]);
                            answers.add(answer);
                        }
                    }
                } else {
                    JSONArray answerArray = question.getJSONArray("answers");
                    if (answerArray != null && !answerArray.isEmpty()) {
                        JSONObject answer = new JSONObject();
                        answer.put("no", 1);
                        answer.put("name", answerArray.getJSONObject(0).getString("answer"));
                        answer.put("content", answerArray.getJSONObject(0).getString("answer"));
                        answers.add(answer);
                    }
                }
            }
        }
        return answers;
    }


    public String getTypeCode(String type) {
        switch (type) {
            case "XD":
                return "GRADE_RANGE";
            case "YEAR":
                return "YEAR";
            case "JJ":
                return "SEMESTER";
            case "NJ":
                return "GRADE";
            case "XK":
                return "SUBJECT";
            case "KCLX":
                return "COURSE_TYPE";
            case "TV":
                return "TEACH_BOOK_VERSION";
        }
        return "";
    }

    /**
     * @return
     */
//    public String getKnowledges() {
//        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE, null);
//        JSONObject result = JSON.parseObject(resultStr);
//        if (result == null || result.getJSONArray("obj") == null) {
//            return "失败了";
//        }
//        JSONArray datas = result.getJSONArray("obj");
//        knowledgeService.truncateTable();
//        int index = 0;
//        for (Object obj : datas) {
//            JSONObject data = JSON.parseObject(obj.toString());
//            SaveKnowledgeRequest request = new SaveKnowledgeRequest();
//            request.setId(String.valueOf(data.getInteger("id")));
//            request.setKnowledgeName(data.getString("name"));
//            request.setParentId(data.getInteger("pId") == -1 ? null : String.valueOf(data.getInteger("pId")));
//            request.setSortIndex(index++);
//            // 学科
//            List<Dictionary> subjects = dictionaryService.queryByName("SUBJECT", data.getString("subName"));
//            String subjectCode = null;
//            if (!subjects.isEmpty()) {
//                subjectCode = subjects.get(0).getCode();
//            }
//            request.setSubject(subjectCode);
//            knowledgeService.addKnowledge(request);
//        }
//        return "成功了";
//    }
    public String getKnowledges() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_ELEMENT, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            if (StringUtils.isEmpty(data.getString("name")) || data.getLong("studySectionId") == null) {
                continue;
            }
            SaveKnowledgeRequest knowledge = new SaveKnowledgeRequest();
            knowledge.setId(data.getLong("id").toString());
            knowledge.setKnowledgeName(data.getString("name"));
            knowledge.setParentId(data.getLong("pId") == null || data.getLong("pId") == 0 ? null : data.getLong("pId").toString());
            knowledge.setSortIndex(data.getInteger("sortId"));
            String gradeRange = getGradeRange(data.getLong("studySectionId"));
            knowledge.setSubject(data.getLong("subjectId") == null ? null : gradeRange + "-" + data.getLong("subjectId").toString());
            knowledgeService.addKnowledg2(knowledge);
        }
        return "成功了";
    }

    /**
     * @return
     */
    public String getBook() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_BOOK, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        knowledgeService.truncateTable();
        Map<String, String> subjects = new HashMap<>();
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            if(StringUtils.isEmpty(data.getString("name")) || data.getLong("teachingId") == null){
                continue;
            }
            BookVersion bookVersion = new BookVersion();
            bookVersion.setId(data.getLong("_id").toString());
            bookVersion.setName(data.getString("name"));
            bookVersion.setVersionId(data.getLong("teachingId").toString());
            bookVersion.setVersionName(data.getString("teachingName"));
            String subjectId = subjects.get(data.getLong("teachingId").toString());
            if (StringUtils.isEmpty(subjectId)) {
                // 查询版本对应的学科
                QueryWrapper<CourseSystem> qw = new QueryWrapper<>();
                qw.eq("relation_type", "TEACH_BOOK_VERSION");
                qw.eq("relation_value", data.getLong("teachingId").toString());
                CourseSystem courseSystem = courseSystemService.selectFirst(qw);
                if (courseSystem == null) {
                    continue;
                }
                subjectId = courseSystem.getSubjectId();
            }
            bookVersion.setSubject(subjectId);
            bookVersion.setSortIndex(index++);
            bookVersionService.insert(bookVersion);
            List<JSONObject> chapters = JSON.parseObject(data.getJSONArray("chapter").toString(), List.class);
            // 按id升序排序
            Collections.sort(chapters, new Comparator<JSONObject>() {
                public int compare(JSONObject a1, JSONObject a2) {
                    int io1 = a1.getInteger("id");
                    int io2 = a2.getInteger("id");
                    if (a1.getInteger("pId") == 0 && a2.getInteger("pId") == 0) {
                        return io1 - io2;
                    } else if (a1.getInteger("pId") == 0 && a2.getInteger("pId") != 0) {
                        return -1;
                    } else if (a1.getInteger("pId") != 0 && a2.getInteger("pId") == 0) {
                        return 1;
                    }
                    return io1 - io2;
                }
            });
            if (chapters != null && !chapters.isEmpty()) {
                for (int i = 0; i < chapters.size(); i++) {
                    JSONObject chapter = chapters.get(i);
                    BookChapterDto bookChapter = new BookChapterDto();
                    bookChapter.setId(data.getLong("_id").toString() + "-" + chapter.getLong("id").toString());
                    bookChapter.setBookVersionId(data.getLong("_id").toString());
                    bookChapter.setParentId(chapter.getLong("pId") == 0 ? null : data.getLong("_id").toString() + "-" + chapter.getLong("pId").toString());
                    bookChapter.setName(chapter.getString("title"));
//                    bookChapter.setSortIndex(chapter.getInteger("sort"));
                    bookChapterService.addBookChapter(bookChapter);
                }
            }
        }
        return "成功了";
    }

    /**
     * @return
     */
    public String getChapter() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_CHAPTERS, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        knowledgeService.truncateTable();
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            SaveKnowledgeRequest request = new SaveKnowledgeRequest();
            request.setId(String.valueOf(data.getInteger("id")));
            request.setKnowledgeName(data.getString("name"));
            request.setParentId(data.getInteger("pId") == -1 ? null : String.valueOf(data.getInteger("pId")));
            request.setSortIndex(index++);
            // 学科
            List<Dictionary> subjects = dictionaryService.queryByName("SUBJECT", data.getString("subName"));
            String subjectCode = null;
            if (!subjects.isEmpty()) {
                subjectCode = subjects.get(0).getCode();
            }
            request.setSubject(subjectCode);
            knowledgeService.addKnowledge(request);
        }
        return "成功了";
    }

    /**
     * @return
     */
    public String getCourses() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_COURSES, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        knowledgeService.deleteByCondition(new QueryWrapper<>());
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Course course = new Course();
            course.setId(data.getLong("id").toString());
            course.setCourseName(data.getString("name"));
            // 班型
            String courseTypeName = data.getString("BX_ID_name");
            List<Dictionary> courseTypes = dictionaryService.queryByName("COURSE_TYPE", courseTypeName);
            String courseTypeId = null;
            if (!courseTypes.isEmpty()) {
                courseTypeId = courseTypes.get(0).getId();
            }
            course.setCourseTypeId(courseTypeId);

            // 年份
            JSONArray years = data.getJSONArray("YEAR_ID_name");
            if (years != null && years.size() > 0) {
                String year = years.getString(0);
                List<Dictionary> yearList = dictionaryService.queryByName("YEAR", year);
                String yearId = null;
                if (!yearList.isEmpty()) {
                    yearId = yearList.get(0).getId();
                }
                course.setYear(yearId);
            }

            // 年级
            JSONArray grades = data.getJSONArray("NJ_ID_name");
            if (grades != null && grades.size() > 0) {
                String gradeName = grades.getString(0);
                List<Dictionary> gradeList = dictionaryService.queryByName("GRADE", gradeName);
                String gradeId = null;
                if (!gradeList.isEmpty()) {
                    gradeId = gradeList.get(0).getId();
                }
                course.setGradeId(gradeId);
            }

            // 学科
            String subjectName = data.getString("XK_ID_name");
            List<Dictionary> subjects = dictionaryService.queryByName("SUBJECT", subjectName);
            String subjectCode = null;
            if (!subjects.isEmpty()) {
                subjectCode = subjects.get(0).getCode();
            }
            course.setSubjectId(subjectCode);

            // 学期
            JSONArray semesters = data.getJSONArray("JJ_ID_name");
            if (semesters != null && semesters.size() > 0) {
                String semesterName = semesters.getString(0);
                List<Dictionary> semesterList = dictionaryService.queryByName("SEMESTER", semesterName);
                String semesterId = null;
                if (!semesterList.isEmpty()) {
                    semesterId = semesterList.get(0).getId();
                }
                course.setSemesterId(semesterId);
            }

            course.setCreatorId(data.getLong("operatorId").toString());
            course.setCreatorName(data.getString("operatorName"));
            Integer indexCount = data.getInteger("kcCount");
            course.setCourseIndexNum(indexCount == null ? 0 : indexCount);
            course.setStatus(indexCount == null ? 0 : indexCount > 0 ? 1 : 0);
            courseService.insert(course);
        }
        return "成功了";
    }

    /**
     * @return
     */
    public String getCourseIndexs() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_COURSES_INDEX, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        knowledgeService.deleteByCondition(new QueryWrapper<>());
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            CourseIndex course = new CourseIndex();
            course.setId(data.getLong("id").toString());
            course.setCourseId(data.getLong("courseId").toString());
            course.setCourseIndexName(data.getString("name"));
            course.setOrderNo(data.getInteger("sortIndex"));
            courseIndexService.insert(course);
        }
        return "成功了";
    }

    /**
     * 部门
     *
     * @return
     */
    public String getOrgs() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_ORGS, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
//        groupService.deleteByCondition(new QueryWrapper<>());
        List<GroupSubject> subjects = new ArrayList<>();
        GroupSubject groupSubject = new GroupSubject();
        groupSubject.setGradeRangeId("primary");
        groupSubject.setSubjectCode("xiaoxueyuwen");
        groupSubject.setSubjectName("小学语文");
        groupSubject.setGradeRangeName("小学");
        subjects.add(groupSubject);
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Group group = new Group();
            group.setId(String.valueOf(data.getInteger("id")));
            group.setName(data.getString("name"));
            group.setSortIndex(index++);
            group.setGroupSubjects(subjects);
            groupService.saveOrUpdateGroup(group);
        }
        return "成功了";
    }


    /**
     * 用户
     *
     * @return
     */
    public String getUsers() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_USERS, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
//        userService.deleteByCondition(new QueryWrapper<>());
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            List<Integer> roleIds = data.getObject("roles", List.class);
            List<Integer> orgIds = data.getObject("orgs", List.class);
            UserRequest user = new UserRequest();
            user.setId(String.valueOf(data.getInteger("id")));
            user.setNickname(data.getString("name"));
            user.setUsername(data.getString("name"));
            user.setRoleIds(roleIds.stream().map(id -> id + "").collect(Collectors.toList()));
            user.setGroupIds(orgIds.stream().map(id -> id + "").collect(Collectors.toList()));
            user.setMobile(data.getString("loginName"));
            user.setPassword(UserAuthUtil.encodePassword(user.getId(), data.getString("password")));
            List<String> schoolIds = new ArrayList<>();
            if (data.getLong("schoolId") != null) {
                schoolIds.add(data.getLong("schoolId").toString());
            }
            user.setSchoolIds(schoolIds);
            userService.addUser(user);
        }
        return "成功了";
    }

    public String getPublicMaterials() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_PUBLIC_MATERIALS, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Material material = new Material();
            material.setId(data.getLong("id").toString());
            material.setFileName(data.getString("name"));
            material.setExt(data.getString("ext"));
            String filePath = data.getString("filePath");
            material.setFilePath(filePath.startsWith("/") ? filePath : "/" + filePath);
            material.setType(getMaterialType(data.getInteger("type")));
            material.setCreatorId(data.getLong("operatorId") != null ? data.getLong("operatorId").toString() : "");
            material.setCreatorName(data.getString("operatorName"));
            material.setIsPublic(1);

            JSONArray jsonArray = data.getJSONArray("libAttrs");
            JSONObject json = jsonArray.getJSONObject(0);
            JSONObject relation = json.getJSONObject("relation");
            if (relation != null) {
                Long subjectId = relation.getLong("XK_ID");
                QueryWrapper<Dictionary> queryWrapper = new QueryWrapper();
                queryWrapper.eq("val", subjectId);
                queryWrapper.eq("type_code", "SUBJECT");
                Dictionary dictionary = dictionaryService.selectFirst(queryWrapper);
                if (dictionary != null) {
                    material.setSubject(dictionary.getCode());
                }
            }
            materialService.insert(material);
            JSONArray courseInfos = json.getJSONArray("courseInfo");
            for (Object obj1 : courseInfos) {
                JSONObject courseInfo = JSON.parseObject(obj1.toString());
                if (courseInfo == null || courseInfo.size() == 0) {
                    continue;
                }
                String courseId = courseInfo.getLong("id").toString();
                if (courseInfo.getJSONArray("lessonIds") != null) {
                    List<Long> indexs = JSON.parseObject(courseInfo.getJSONArray("lessonIds").toJSONString(), List.class);
                    QueryWrapper<CourseIndex> qw = new QueryWrapper<>();
                    qw.eq("course_id", courseId);
                    qw.in("order_no", indexs);
                    List<CourseIndex> indexList = courseIndexService.queryByCondition(qw);
                    for (CourseIndex courseIndex : indexList) {
                        // 添加到res_material_course_index表中
                        MaterialCourseIndex materialCourseIndex = new MaterialCourseIndex();
                        materialCourseIndex.setMaterialId(material.getId());
                        materialCourseIndex.setCourseIndexId(courseIndex.getId());
                        materialCourseIndexService.insert(materialCourseIndex);
                    }
                }
            }
        }
        return "成功了";
    }

    public String getPrivateMaterials() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_PRIVATE_MATERIALS, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        int index = 0;
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Material material = new Material();
            material.setId(data.getLong("id").toString());
            material.setFileName(data.getString("name"));
            material.setExt(data.getString("ext"));
            String filePath = data.getString("filePath");
            material.setFilePath(filePath.startsWith("/") ? filePath : "/" + filePath);
            material.setType(getMaterialType(data.getInteger("type")));
            material.setCreatorId(data.getLong("operatorId") != null ? data.getLong("operatorId").toString() : "");
            material.setCreatorName(data.getString("operatorName"));
            material.setIsPublic(0);

            JSONArray jsonArray = data.getJSONArray("libAttrs");
            JSONObject json = jsonArray.getJSONObject(0);
            JSONArray courseInfos = json.getJSONArray("courseInfo");
            JSONObject relation = json.getJSONObject("relation");
            if (relation != null) {
                Long subjectId = relation.getLong("XK_ID");
                QueryWrapper<Dictionary> queryWrapper = new QueryWrapper();
                queryWrapper.eq("val", subjectId);
                queryWrapper.eq("type_code", "SUBJECT");
                Dictionary dictionary = dictionaryService.selectFirst(queryWrapper);
                if (dictionary != null) {
                    material.setSubject(dictionary.getCode());
                }
            }
            materialService.insert(material);
            for (Object obj1 : courseInfos) {
                JSONObject courseInfo = JSON.parseObject(obj1.toString());
                if (courseInfo == null || courseInfo.size() == 0) {
                    continue;
                }
                String courseId = courseInfo.getLong("id").toString();
                if (courseInfo.getJSONArray("lessonIds") != null) {
                    List<Long> indexs = JSON.parseObject(courseInfo.getJSONArray("lessonIds").toJSONString(), List.class);
                    QueryWrapper<CourseIndex> qw = new QueryWrapper<>();
                    qw.eq("course_id", courseId);
                    qw.in("order_no", indexs);
                    List<CourseIndex> indexList = courseIndexService.queryByCondition(qw);
                    for (CourseIndex courseIndex : indexList) {
                        // 添加到res_material_course_index表中
                        MaterialPrepare materialPrepare = new MaterialPrepare();
                        materialPrepare.setMaterialId(material.getId());
                        materialPrepare.setCourseId(courseId);
                        materialPrepare.setCourseIndexId(courseIndex.getId());
                        materialPrepareService.insert(materialPrepare);
                    }
                }
            }
        }
        //
        return "成功了";
    }

    private Integer getMaterialType(Integer type) {
        if (type == null) {
            return 4;
        }
        //1:课件 2:讲义 3:图片 4:音频 5:视频 6:其他
        // 1课件 2 讲义教案 3 说课视频 4 其他 5 标准教案
        switch (type) {
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 4;
            case 4:
                return 3;
            case 5:
                return 3;
            case 6:
                return 4;

        }
        return 4;
    }

    private static Map<String, Integer> questionTypes = new LinkedHashMap<>();

    static {
        questionTypes.put("单选题", 1);
        questionTypes.put("多选题", 2);
        questionTypes.put("填空题", 3);
        questionTypes.put("判断题", 4);
        questionTypes.put("解答题", 5);
        questionTypes.put("完形填空", 10);
        questionTypes.put("连线题", 888);
        questionTypes.put("阅读理解", 9);
        questionTypes.put("综合题", 888);
        questionTypes.put("作文", 888);
    }

    public String getQuestionType(String type) {
        switch (type) {
            case "ST_dx":
                return "单选题";
            case "ST_dxx":
                return "多选题";
            case "ST_tk":
                return "填空题";
            case "ST_djtk":
                return "单句填空";
            case "ST_wxtk":
                return "完形填空";
            case "ST_dwtk":
                return "短文填空";
            case "ST_dwgc":
                return "短文改错";
            case "ST_bqdh":
                return "补全对话";
            case "ST_fy":
                return "翻译";
            case "ST_pd":
                return "判断题";
            case "ST_lx":
                return "连线题";
            case "ST_jd":
                return "解答题";
            case "ST_zh":
                return "综合题";
            case "ST_ydlj":
                return "阅读理解";
            case "ST_ydtkwxw":
                return "阅读填空(五选五)";
            case "ST_ydtkqxw":
                return "阅读填空(七选五)";
            case "ST_rwxyd":
                return "任务型阅读";
            case "ST_yd":
                return "阅读";
            case "ST_cz":
                return "操作";
            case "ST_zt":
                return "作图";
            case "ST_sy":
                return "实验";
            case "ST_smbd":
                return "书面表达";
            case "ST_zw":
                return "作文";
            default:
                return "解答题";
        }
    }

    public String getQuestionTypes() {
        List<Dictionary> subjects = dictionaryService.queryByTypeCode("SUBJECT");
        for (Dictionary subject : subjects) {
            int index = 0;
            for (Map.Entry<String, Integer> entry : questionTypes.entrySet()) {
                index++;
                QuestionTypeRelation relation = new QuestionTypeRelation();
                relation.setJyQuestionType(index);
                relation.setJyQuestionTypeName(entry.getKey());
                relation.setToolQuestionType(entry.getValue());
                relation.setToolQuestionTypeName(entry.getKey());
                relation.setSubjectId(subject.getCode());
                relation.setSubjectName(subject.getName());
                questionTypeRelationService.insert(relation);
            }
        }
        return "成功了";
    }

    public String getAllMaterial() {
        getPublicMaterials();
        getPrivateMaterials();
        return "成功了";
    }

    public String getPapers() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_PAPER, null);
        JSONObject result = JSON.parseObject(resultStr);
        if (result == null || result.getJSONArray("obj") == null) {
            return "失败了";
        }
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            Paper paper = new Paper();
            paper.setId(data.getLong("id").toString());
            QueryWrapper<Dictionary> queryWrapper = new QueryWrapper();
            queryWrapper.eq("val", data.getLong("XK_ID"));
            queryWrapper.eq("type_code", "SUBJECT");
            Dictionary dictionary = dictionaryService.selectFirst(queryWrapper);
            paper.setSubjectId(dictionary.getCode());
            List<Dictionary> grades = dictionaryService.queryByName("GRADE", data.getString("NJ_ID_name"));
            paper.setGradeId(grades.isEmpty() ? null : grades.get(0).getId());
            List<Dictionary> dictionarys = dictionaryService.queryByName("YEAR", data.getString("year"));
            paper.setYear(dictionarys.isEmpty() ? null : dictionarys.get(0).getId());
            paper.setType(1);
            paper.setSourceFrom(3);
            paper.setTitle(data.getString("name"));
            JSONObject library = data.getJSONObject("library");
            if(library == null){
                continue;
            }
            String filePath = library.getString("filePath");
            paper.setFilePath(filePath.startsWith("/") ? filePath : "/" + filePath);
            paper.setCreateTime(data.getDate("createTime"));
            paper.setCreatorId(data.getLong("operatorId") == null ? null : data.getLong("operatorId").toString());
            paper.setCreatorName(data.getString("operatorName"));
            paper.setIsPublic(1);
            paper.setCheckStatus(2);
            paperService.insert(paper);
        }
        return "成功了";
    }

    public String getSchools() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_SCHOOL, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            School school = new School();
            school.setSchoolName(data.getString("name"));
            school.setId(data.getLong("id").toString());
            school.setSchoolAddress(data.getString("address"));
            school.setDeleted(0);
            schoolService.insert(school);
        }
        return "成功了";
    }

    public String getKnowledgeTemplate() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_TEMPLATE, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            KnowledgeTemplate template = new KnowledgeTemplate();
            template.setId(data.getLong("id").toString());
            template.setTitle(data.getString("name"));
            String gradeRange = getGradeRange(data.getLong("studySectionId"));
            Dictionary subject = dictionaryService.queryByCode(gradeRange + "-" + data.getLong("subjectId").toString(), "SUBJECT");
            if (subject == null) {
                continue;
            }
            template.setSubjectId(subject.getId());
            template.setStatus(0);
            template.setDeleted(0);
            knowledgeTemplateService.insert(template);
        }
        return "成功了";
    }

    public String getKnowledgeTemplateModule() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_TEMPLATE_TREE, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            KnowledgeTemplateModule templateModule = new KnowledgeTemplateModule();
            templateModule.setId(data.getLong("id").toString());
            templateModule.setTitle(data.getString("title"));
            templateModule.setPid(data.getLong("templateId").toString());
            templateModule.setLevel(1);
            templateModule.setSort(data.getInteger("sortId"));
            templateModule.setSubtype("1,2,3,4");
            templateModule.setDeleted(0);
            knowledgeTemplateModuleService.insert(templateModule);
        }
        return "成功了";
    }

    public String getKnowledgeElement() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_ELEMENT, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            KnowledgeElement knowledgeElement = new KnowledgeElement();
            knowledgeElement.setId(data.getLong("id").toString());
            knowledgeElement.setName(data.getString("name"));
            knowledgeElement.setPid(data.getLong("pId") == null ? null : data.getLong("pId").toString());
            knowledgeElement.setSortNum(data.getInteger("sortId"));
            String gradeRange = getGradeRange(data.getLong("studySectionId"));
            knowledgeElement.setSubjectId(data.getLong("subjectId") == null ? null : gradeRange + "-" + data.getLong("subjectId").toString());
            knowledgeElement.setDeleted(0);
            knowledgeElementService.insert(knowledgeElement);
        }
        return "成功了";
    }

    public String getKnowledgeManager() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_MANAGER, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            KnowledgeManager knowledgeManager = new KnowledgeManager();
            knowledgeManager.setId(data.getLong("id").toString());
            knowledgeManager.setTitle(data.getString("title"));
            String knowledgeId = data.getLong("knowledgeElementId") == null ? null : data.getLong("knowledgeElementId").toString();
            knowledgeManager.setKnowledgeId(knowledgeId);
            String gradeRange = getGradeRange(data.getLong("studySectionId"));
            knowledgeManager.setSubjectId(data.getLong("subjectId") == null ? null : gradeRange + "-" + data.getLong("subjectId").toString());
            //TODO: 不知道没有影响
            knowledgeManager.setTemplateId(null);
            knowledgeManager.setDeleted(0);
            knowledgeManagerService.insert(knowledgeManager);
            if (StringUtils.isNotEmpty(knowledgeId)) {
                KnowledgeManagerElementRelation knowledgeManagerElementRelation = new KnowledgeManagerElementRelation();
                knowledgeManagerElementRelation.setManageId(knowledgeManager.getId());
                knowledgeManagerElementRelation.setKnowledgeId(knowledgeId);
                knowledgeManagerElementRelationService.insert(knowledgeManagerElementRelation);
            }
        }
        return "成功了";
    }

    public String getKnowledgeContent() {
        List<KnowledgeManager> knowledgeManagers = knowledgeManagerService.queryAll();
        for (KnowledgeManager knowledgeManager : knowledgeManagers) {
            Map<String, String> params = new HashMap<>(1);
            params.put("handoutInfoId", knowledgeManager.getId());
            String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_TREE_BY_HANDINFOID, params);
            JSONObject result = JSON.parseObject(resultStr);
            JSONArray list = result.getJSONArray("obj");
            int sort = 0;
            for (Object obj : list) {
                JSONObject data = JSON.parseObject(obj.toString());
                // 原先的数据 title 和 content 在一起，所以一条数据要拆成两条
                KnowledgeContent knowledgeContent = new KnowledgeContent();
                knowledgeContent.setId(data.getLong("id").toString());
                knowledgeContent.setTitle(data.getString("title"));
                String moduleId = data.getLong("handoutId") == null ? null : data.getLong("handoutId").toString();
                knowledgeContent.setModuleId(moduleId);
                knowledgeContent.setKnowledgeId(data.getLong("knowledgeId") == null ? null : data.getLong("knowledgeId").toString());
                knowledgeContent.setType(1);
                knowledgeContent.setContent("1,2,3,4");
                knowledgeContent.setSortNum(sort);
                knowledgeContentService.insert(knowledgeContent);

                knowledgeContent = new KnowledgeContent();
                knowledgeContent.setModuleId(moduleId);
                knowledgeContent.setId(data.getLong("id").toString());
                // 文本
                if ("W".equals(data.getString("type"))) {
                    knowledgeContent.setContent(data.getString("content"));
                    knowledgeContent.setType(2);
                    knowledgeContent.setPid(data.getLong("pId").toString());
                    knowledgeContent.setSortNum(sort++);
                    knowledgeContent.setDeleted(0);
                    knowledgeContentService.insert(knowledgeContent);
                }
                //
//                if ("S".equals(data.getString("type"))) {
//                    if (StringUtils.isEmpty(data.get("content").toString())) {
//                        continue;
//                    }
//                    if (data.get("content") instanceof JSONArray) {
//                        JSONArray contents = data.getJSONArray("content");
//                        for (int i = 0; i < contents.size(); i++) {
//                            JSONObject content = contents.getJSONObject(i);
//                            Integer type = content.getInteger("type");
//                            if (type == 1) {
//                                // 标题
//                                knowledgeContent = new KnowledgeContent();
//                                knowledgeContent.setContent(content.getString("title"));
//                                knowledgeContent.setType(1);
//                                knowledgeContent.setSortNum(sort++);
//                                knowledgeContent.setDeleted(0);
//                                knowledgeContentService.insert(knowledgeContent);
//
//                                knowledgeContent.setId(null);
//                                String contentStr = data.getString("content");
//                                if (contentStr.startsWith("data:image/png;base64,")) {
//                                    contentStr = "<img src=\"" + contentStr + "\"/>";
//                                }
//                                knowledgeContent.setContent(contentStr);
//                                knowledgeContent.setType(2);
//                                knowledgeContent.setSortNum(sort++);
//                                knowledgeContent.setDeleted(0);
//                                knowledgeContentService.insert(knowledgeContent);
//                                continue;
//                            }
//                            if (type == 2) {
//                                knowledgeContent = new KnowledgeContent();
//                                knowledgeContent.setContent(content.getLong("id").toString());
//                                knowledgeContent.setType(4);
//                                knowledgeContent.setSortNum(sort++);
//                                knowledgeContent.setDeleted(0);
//                                knowledgeContentService.insert(knowledgeContent);
//                                continue;
//                            }
//                        }
//                    } else {
//                        JSONObject contents = data.getJSONObject("content");
//                        JSONArray texts = contents.getJSONArray("textList");
//                        for (int i = 0; i < texts.size(); i++) {
//                            JSONObject text = texts.getJSONObject(i);
//                            // 标题
//                            knowledgeContent = new KnowledgeContent();
//                            knowledgeContent.setContent(text.getString("title"));
//                            knowledgeContent.setType(1);
//                            knowledgeContent.setSortNum(sort++);
//                            knowledgeContent.setDeleted(0);
//                            knowledgeContentService.insert(knowledgeContent);
//
//                            knowledgeContent.setId(null);
//                            String contentStr = text.getString("content");
//                            if (contentStr.startsWith("data:image/png;base64,")) {
//                                contentStr = "<img src=\"" + contentStr + "\"/>";
//                            }
//                            knowledgeContent.setContent(contentStr);
//                            knowledgeContent.setType(2);
//                            knowledgeContent.setSortNum(sort++);
//                            knowledgeContent.setDeleted(0);
//                            knowledgeContentService.insert(knowledgeContent);
//                            continue;
//                        }
//                        JSONArray quesList = contents.getJSONArray("quesList");
//                        for (int i = 0; i < quesList.size(); i++) {
//                            JSONObject questions = quesList.getJSONObject(i);
//                            for (String key : questions.keySet()) {
//                                if (!key.startsWith("ST_")) {
//                                    continue;
//                                }
//                                JSONArray questionsList = questions.getJSONArray(key);
//                                for (int i1 = 0; i1 < questionsList.size(); i1++) {
//                                    JSONObject questionsInfo = questionsList.getJSONObject(i1);
//                                    JSONObject question = questionsInfo.getJSONObject("content");
//                                    KnowledgeContent knowledgeContentQuestion = new KnowledgeContent();
//                                    knowledgeContentQuestion.setContent(question.getLong("id").toString());
//                                    knowledgeContentQuestion.setType(4);
//                                    knowledgeContentQuestion.setSortNum(sort++);
//                                    knowledgeContentQuestion.setDeleted(0);
//                                    knowledgeContentService.insert(knowledgeContent);
//                                }
//                            }
//                        }
//                    }
//                    continue;
//                }
                // 试题
                if ("Q".equals(data.getString("type"))) {
                    Object content = data.get("content");
                    if (content instanceof String) {
                        continue;
                    }
                    JSONArray questions = data.getJSONArray("content");
                    if (questions.isEmpty()) {
                        continue;
                    }
                    for (int i = 0; i < questions.size(); i++) {
                        JSONObject question = questions.getJSONObject(i);
                        knowledgeContent = new KnowledgeContent();
                        knowledgeContent.setModuleId(moduleId);
                        knowledgeContent.setId(data.getLong("id").toString());
                        knowledgeContent.setPid(data.getLong("pId").toString());
                        knowledgeContent.setContent(question.getLong("id").toString());
                        knowledgeContent.setType(4);
                        knowledgeContent.setSortNum(sort++);
                        knowledgeContent.setDeleted(0);
                        knowledgeContentService.insert(knowledgeContent);
                    }
                }
            }
        }
        return "成功了";
    }

    private Integer getType(String type) {
        if (StringUtils.isEmpty(type) || "W".equals(type)) {
            return 2;
        }
        if ("X".equals(type)) {
            return 3;
        }
        if ("Q".equals(type)) {
            return 4;
        }
        return 2;
    }

    public String getHandout() {
        String resultStr = HttpUtils.postRequest(UrlConstants.URL_HANDOUT, null);
        JSONObject result = JSON.parseObject(resultStr);
        JSONArray datas = result.getJSONArray("obj");
        for (Object obj : datas) {
            JSONObject data = JSON.parseObject(obj.toString());
            String title = data.getString("title");
            if (StringUtils.isEmpty(title) || RegexUtils.Match(title, "^-?\\d+(\\.\\d+)?$")) {
                continue;
            }
            Material material = new Material();
            material.setId(data.getLong("id").toString());
            material.setFileName(data.getString("title"));
            String gradeRange = getGradeRange(data.getLong("studySectionId"));
            material.setSubject(gradeRange + "-" + data.getLong("subjectId").toString());
            // 类型：1课件  2 讲义教案  3 说课视频  4 其他 5 标准教案
            material.setIsPublic(1);
            material.setType(2);
            material.setDeleted(0);
            materialService.insert(material);
            MaterialChapter materialChapter = new MaterialChapter();
            materialChapter.setMaterialId(material.getId());
            JSONObject chapter = data.getJSONObject("chapterObj");
            if (chapter == null) {
                continue;
            }
            materialChapter.setChapterId(data.getLong("bookId").toString() + "-" + chapter.getInteger("id").toString());
            materialChapter.setDeleted(0);
            materialChapterService.insert(materialChapter);
        }
        return "成功了";
    }

    public String getHandoutDetail() {
        List<Material> materials = materialService.queryAll();
        for (Material material : materials) {
            Map<String, String> params = new HashMap<>(1);
            params.put("handoutInfoId", material.getId());
            String resultStr = HttpUtils.postRequest(UrlConstants.URL_KNOWLEDGE_TREE_BY_HANDINFOID, params);
            JSONObject result = JSON.parseObject(resultStr);
            JSONArray list = result.getJSONArray("obj");
            List<JSONObject> details = sortHandoutDetails(list);
            Integer sort = 0;
            for (JSONObject data : details) {
//                JSONObject data = JSON.parseObject(obj.toString());
                // 标题
                HandoutNode handoutNode = new HandoutNode();
                handoutNode.setId(data.getLong("id").toString());
                handoutNode.setHandoutId(material.getId());
                handoutNode.setContent(data.getString("title"));
                handoutNode.setType(1);
                handoutNode.setSortNum(sort++);
                handoutNode.setDeleted(0);
                handoutNodeService.insert(handoutNode);
                // 文本
                if ("W".equals(data.getString("type"))) {
                    handoutNode = new HandoutNode();
                    handoutNode.setHandoutId(material.getId());
                    String content = data.getString("content");
                    if (content.startsWith("data:image/png;base64,")) {
                        content = "<img src=\"" + content + "\"/>";
                    }
                    handoutNode.setContent(content);
                    handoutNode.setType(2);
                    handoutNode.setSortNum(sort++);
                    handoutNode.setDeleted(0);
                    handoutNodeService.insert(handoutNode);
                    continue;
                }
                if ("S".equals(data.getString("type"))) {
                    if (StringUtils.isEmpty(data.get("content").toString())) {
                        continue;
                    }
                    if (data.get("content") instanceof JSONArray) {
                        JSONArray contents = data.getJSONArray("content");
                        for (int i = 0; i < contents.size(); i++) {
                            JSONObject content = contents.getJSONObject(i);
                            Integer type = content.getInteger("type");
                            if (type == 1) {
                                // 标题
                                handoutNode.setId(null);
                                handoutNode.setHandoutId(material.getId());
                                handoutNode.setContent(content.getString("title"));
                                handoutNode.setType(1);
                                handoutNode.setSortNum(sort++);
                                handoutNode.setDeleted(0);
                                handoutNodeService.insert(handoutNode);

                                handoutNode.setId(null);
                                String contentStr = data.getString("content");
                                if (contentStr.startsWith("data:image/png;base64,")) {
                                    contentStr = "<img src=\"" + contentStr + "\"/>";
                                }
                                handoutNode.setContent(contentStr);
                                handoutNode.setType(2);
                                handoutNode.setSortNum(sort++);
                                handoutNode.setDeleted(0);
                                handoutNodeService.insert(handoutNode);
                                continue;
                            }
                            if (type == 2) {
                                handoutNode.setId(null);
                                handoutNode.setContent(content.getLong("id").toString());
                                handoutNode.setType(4);
                                handoutNode.setSortNum(sort++);
                                handoutNode.setDeleted(0);
                                handoutNodeService.insert(handoutNode);
                                continue;
                            }
                        }
                    } else {
                        JSONObject contents = data.getJSONObject("content");
                        JSONArray texts = contents.getJSONArray("textList");
                        for (int i = 0; i < texts.size(); i++) {
                            JSONObject text = texts.getJSONObject(i);
                            // 标题
                            handoutNode.setId(null);
                            handoutNode.setContent(text.getString("title"));
                            handoutNode.setType(1);
                            handoutNode.setSortNum(sort++);
                            handoutNode.setDeleted(0);
                            handoutNodeService.insert(handoutNode);

                            handoutNode.setId(null);
                            String contentStr = text.getString("content");
                            if(StringUtils.isEmpty(contentStr)){
                                continue;
                            }
                            if (contentStr.startsWith("data:image/png;base64,")) {
                                contentStr = "<img src=\"" + contentStr + "\"/>";
                            }
                            handoutNode.setContent(contentStr);
                            handoutNode.setType(2);
                            handoutNode.setSortNum(sort++);
                            handoutNode.setDeleted(0);
                            handoutNodeService.insert(handoutNode);
                            continue;
                        }
                        JSONArray quesList = contents.getJSONArray("quesList");
                        if (quesList == null) {
                            continue;
                        }
                        for (int i = 0; i < quesList.size(); i++) {
                            JSONObject questions = quesList.getJSONObject(i);
                            for (String key : questions.keySet()) {
                                if (!key.startsWith("ST_")) {
                                    continue;
                                }
                                JSONArray questionsList = questions.getJSONArray(key);
                                for (int i1 = 0; i1 < questionsList.size(); i1++) {
                                    JSONObject questionsInfo = questionsList.getJSONObject(i1);
                                    JSONObject question = questionsInfo.getJSONObject("content");
                                    HandoutNode handoutNode1 = new HandoutNode();
                                    handoutNode1.setHandoutId(material.getId());
                                    handoutNode1.setContent(question.getLong("id").toString());
                                    handoutNode1.setType(4);
                                    handoutNode1.setSortNum(sort++);
                                    handoutNode1.setDeleted(0);
                                    handoutNodeService.insert(handoutNode1);
                                }
                            }
                        }
                        continue;
                    }
                }
                // 试题
                if ("Q".equals(data.getString("type"))) {
                    Object content = data.get("content");
                    if (content instanceof String) {
                        continue;
                    }
                    JSONArray questions = data.getJSONArray("content");
                    if (questions.isEmpty()) {
                        continue;
                    }
                    for (int i = 0; i < questions.size(); i++) {
                        JSONObject question = questions.getJSONObject(i);
                        HandoutNode handoutNode1 = new HandoutNode();
                        handoutNode1.setHandoutId(material.getId());
                        handoutNode1.setContent(question.getLong("id").toString());
                        handoutNode1.setType(4);
                        handoutNode1.setSortNum(sort++);
                        handoutNode1.setDeleted(0);
                        handoutNodeService.insert(handoutNode1);
                    }
                }
            }
        }
        return "成功了";
    }

    private List<JSONObject> sortHandoutDetails(JSONArray array){
        List<JSONObject> list = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject data = array.getJSONObject(i);
            Long pId = data.getLong("pId");
            if(pId == 0){
                list.add(data);
                Long id = data.getLong("id");
                sortByPid(array, id, list);
            }
        }
        return list;
    }

    private void sortByPid(JSONArray array, Long pid, List<JSONObject> list){
        for (int i1 = 0; i1 < array.size(); i1++) {
            JSONObject data = array.getJSONObject(i1);
            if(pid.longValue() == data.getLong("pId").longValue()){
                list.add(data);
                sortByPid(array,data.getLong("id"),list);
            }
        }
    }
}